package client.gui;

//import java.awt.*;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.*;

import javax.swing.*;
import messages.*;
import messages.MessageExecuteExamCodeCheckReply.ErrMsg;
import sharedspace.*;
import java.awt.Color;



/**
 * This class is a panel that responsible to show all the student options
 * @author Amir S.
 * @author Jacob C.
 * @author Maya G.
 * @author Michael V.
 *
 */
public class GUI_Student extends GUI_AbstractMainMenu {
	private static final long serialVersionUID = 1L;

	private Student student = null;
	private ExecuteTest executeTest;
	private Client_GUI ms = null;
	private JTable testToDoTable;
	private JScrollPane testToDoScroller;
	private List<ExecuteTest> eList;
	private List<Executetestinfo> eiList;
	private JLabel title;
	
	boolean emptyUNflag=false;
	boolean emptyPWflag=false;
	
  	//public Client_GUI ms=null;
  

	private JButton executeExam = null;
	private JButton watchGade = null;
	/**
	 * This is the default constructor
	 * @param MS
	 */
	public GUI_Student(Client_GUI MS, Student student) {
		super(MainMenuType.STUDENT,MS);
		background.setLocation(10, 0);
		greetMsg.setText("Welcome "+MS.lg.getCurrentUsername()+"!");
		mainMenu.setText("Student");
		this.student = student;
		this.ms = MS;
		initiateStudent();
		//background.add(getExecuteExam(), null);
		
	}

	/**
	 * This method initializes the student screen
	 */
	private void initiateStudent() {
			
		
		this.setSize(1000, 700);	
		this.setLayout(null);
		
		background.add(getWatchExam(), null);
		background.add(getExecuteExam(), null);
		try {
			//Sending the student message to server to get student extra details
			MessageStudent msgStd = new MessageStudent(this.student);
			ms.client.sendToServer(msgStd);
			

		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		MessageStudent msgStd= (MessageStudent)ms.client.GetMessage();
		this.student = msgStd.getStudent();
		this.eList = msgStd.geteList();
		this.eiList = msgStd.getEiList();
		background.add(getTestToDoTable(),null);
		title = new JLabel();
		title.setForeground(Color.BLUE);
		title.setBounds(314, 139, 586, 50);
		background.add(title);
		title.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 30));
		title.setText("Test to do in year: "+DateUtils.currentYear()+" in semester: " +DateUtils.currentSemester());
		
	}
	
	private JButton getExecuteExam()
	{
		if (this.executeExam == null){
			//Set Graphics
			this.executeExam = new JButton();
			this.executeExam.setFont(new Font("Arial",Font.PLAIN , 16));
			this.executeExam.setBounds(new Rectangle(109, 200, 157, 34));
			this.executeExam.setText("Exexute Exam");
			
			//Button "executeExam" pressed
			this.executeExam.addActionListener(new java.awt.event.ActionListener() {
				/**
				 * action listener to start test
				 */
				public void actionPerformed(java.awt.event.ActionEvent e) {
					System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
					try{
						//insert code
						String code = null;
						code = JOptionPane.showInputDialog(null, "Insert code");
						//checkCodeInput(code) check if input is valid
						if(checkCodeInput(code))
						{
							MessageExecuteExamCheckCode msgEebs = new MessageExecuteExamCheckCode(student, code);
							//Sending the MessageExecuteExamCheckCode message to server
							System.out.println(student.getUserFirstName() +" " + msgEebs.getExamCode());
							ms.client.sendToServer(msgEebs);
							//Getting reply to MessageExecuteExamCheckCodeReply from server
							MessageExecuteExamCodeCheckReply msgEebsrep = (MessageExecuteExamCodeCheckReply) ms.client.GetMessage();
							executeTest = msgEebsrep.getExecuteTest();
							if (msgEebsrep.getError()==ErrMsg.CODE_CORRECT_COMP)
							{
	                    		JOptionPane.showMessageDialog(null,msgEebsrep.GetErrorMessage(0));//code correct
	                    		JOptionPane.showMessageDialog(null, msgEebsrep.GetErrorMessage(2));// test is computerized
	                    		
	                    		MessageExecuteExamGetExam msgeege = new MessageExecuteExamGetExam(executeTest);
	                    		//Sending the MessageExecuteExamGetExam message to server
	        					ms.client.sendToServer(msgeege);
	        					//Getting reply to MessageExecuteExamGetExamReply from server
	        					MessageExecuteExamGetExamReply msgeegerep = (MessageExecuteExamGetExamReply)ms.client.GetMessage();
	        					//display the computerized form
	        					displayTest(msgeegerep.getQuestionInTestList(), msgeegerep.getCourse());
	        					 
							}
							else if (msgEebsrep.getError()==ErrMsg.CODE_CORRECT_WORD)
							{
								// TODO operate word test file
								JOptionPane.showMessageDialog(null,msgEebsrep.GetErrorMessage(0));//code correct
	                    		JOptionPane.showMessageDialog(null, msgEebsrep.GetErrorMessage(3));// test is manual
								ms.mt = new GUI_ManualTest(ms, msgEebsrep.getExecuteTest(), student);
								ms.setContentPane(ms.mt);
	                    	
							}
							else if (msgEebsrep.getError()==ErrMsg.CODE_INCORRECT)
							{
								JOptionPane.showMessageDialog(null,msgEebsrep.GetErrorMessage(1));//code incorrect
							}
						}
												
						}
					catch (IOException e1){
						// TODO Auto-generated catch block
						e1.printStackTrace();
						}
				}
			}
			);
		}
		return this.executeExam;
	}
	
	private JButton getWatchExam()
	{
		if (this.watchGade == null) {
			this.watchGade = new JButton();
			this.watchGade.setFont(new Font("Arial",Font.PLAIN , 16));
			this.watchGade.setBounds(new Rectangle(109, 245, 157, 34));
			this.watchGade.setText("Exams' grades");
			
			//Button "watchGade" pressed
			this.watchGade.addActionListener(new java.awt.event.ActionListener() {
				
				public void actionPerformed(java.awt.event.ActionEvent e) {
					System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
					ms.svg = new GUI_Student_ViewGrades(ms, student);
					if (ms.svg.b == true)
					{	/*open GUI of student result*/
						ms.setContentPane(ms.svg);
						ms.svg.backButton.addActionListener(new ActionListener() {
						
							@Override
							public void actionPerformed(ActionEvent e) {
								// TODO Auto-generated method stub
								ms.setContentPane(ms.stdnt);	
							}
						});
					}
				}}
			);
			
			
		}
		
		return this.watchGade;
	}
	/**
	 * check if input of code is correct
	 * @param code
	 * @return
	 */
	public boolean checkCodeInput(String code)
	{
		if (code!=null)
		{int codeLength = code.length();
		
		if (codeLength != 4)
		{
			//code is not 4 characters
			JOptionPane.showMessageDialog(null,"code need to be combined from 4 characters");
			return false;
		}
		int i;
		// check each character code 
		for (i = 0; i<4; i++ )
		{
			char ch =  code.charAt(i);
			if (ch<'0' || ch>'9' )
				if (ch<'A' || ch>'Z')
					if (ch<'a' || ch>'z'){
				JOptionPane.showMessageDialog(null,"on of the characters is not a number or letter");
				return false;
					}
			
				
		}
		//JOptionPane.showMessageDialog(null,"code input is ok");
		return true;}
		return false;
	}
	/**
	 * make table of test in semester of student
	 * @return
	 */
	public JScrollPane getTestToDoTable()
	{
		String columnNames[] = {"Subject","Course","Date","Test type"};
		String tableModel[][] = new String[eList.size()][4];
		
			for (int i = 0; i<eList.size(); i++)
			{
				tableModel[i][0] = eList.get(i).getTest().getSubject().getSubjectName();
				tableModel[i][1] = eList.get(i).getTest().getCourse().getCourseName();
				tableModel[i][2] = eiList.get(i).getStartTime().toString();
				tableModel[i][3] = eList.get(i).getTestType();
			}
		
		testToDoTable = new JTable(tableModel, columnNames){
			   /**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int rowIndex, int colIndex) {
			   return false; //Disallow the editing of any cell
			   }
			   };
			   
		testToDoTable.setFont(new Font("Tahoma", Font.PLAIN,14));
		testToDoTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		testToDoTable.getTableHeader().setReorderingAllowed(false);
		testToDoScroller = new JScrollPane(testToDoTable);
		testToDoScroller.setBounds(300, 200, 600, 406);
		
		
		return testToDoScroller;
		
		
		
	}
	/**
	 * open new window of computerized test form
	 * @param questionInTestList
	 * @param course
	 */
	public void displayTest(List<QuestionInTest> questionInTestList, Course course)
	{
		ms.cmpt = new GUI_ComputerizeTest(this.ms,questionInTestList, course);
		ms.setContentPane(ms.cmpt);
	}
	
	public Student getStudent()
	{
		return this.student;
	}

	public ExecuteTest getExecuteTest() {
		return executeTest;
	}

	public void setExecuteTest(ExecuteTest executeTest) {
		this.executeTest = executeTest;
	}
}  

